package cn.uncode.util.log.filter;


import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import cn.uncode.util.log.ExtPatternParser;

public class TraceNoFilter implements Filter {
	private static Logger log = LoggerFactory.getLogger(TraceNoFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	String sid=RandomStringUtils.randomAlphanumeric(12);
    	String ip = request.getRemoteAddr();
    	try{
    		Map<String, Object> map = ExtPatternParser.TH_LOCAL.get();
    		if(map!=null){
    			map.put(ExtPatternParser.MARK_SID, sid);
    			map.put(ExtPatternParser.MARK_IP, ip);
    		}
    	}catch(Exception e){
    		log.info(e.getMessage(), e);
    	}
        try {
            chain.doFilter(request, response);
        } finally {
        	try{
        		Map<String, Object> map = ExtPatternParser.TH_LOCAL.get();
        		if(map!=null){
        			map.remove(ExtPatternParser.MARK_SID);
        			map.remove(ExtPatternParser.MARK_IP);
        		}
        	}catch(Exception e){
        		log.info(e.getMessage(), e);
        	}
        }
    }

    @Override
    public void destroy() {

    }
    public static void newTraceNo() {
        MDC.put("traceNo", RandomStringUtils.randomAlphanumeric(12));
    }

    public static void newTraceNo(String parentTranceNo) {
        if (StringUtils.isNotEmpty(parentTranceNo)) {
            MDC.put("traceNo", parentTranceNo + "-" + RandomStringUtils.randomAlphanumeric(6));
        } else {
            newTraceNo();
        }
    }

    public static String getTraceNo() {
        return MDC.get("traceNo");
    }

    public static void clearTraceNo() {
        MDC.remove("traceNo");
    }
}
